<?php

namespace app\common\behavior;


use think\Hook;

class Approve
{
    // 进入审批流程
    public function approveIngWait(&$params)
    {
        $approve = $params['approve'];
        $user_ids = explode(',', $approve['user_ids']);
        $wait_uid = $approve->wait_uid;
        //如果待审批人不存在，则从第一个人开始审批
        if (!$wait_uid){
            $approve->wait_uid = $user_ids[0];
            $approve->save();

            //给审批人发微信通知
            $data['approve'] = $approve;
            $data['action'] = 'wait';
            Hook::listen('send_sp_message',$data);

            return $approve;
        }
        //如果待审批人存在，切换至下一个待审批人
        $uid = $this->arrayNextVal($user_ids, $wait_uid);
        if ($uid){
            $approve->wait_uid = $uid;
            $approve->save();

            //给审批人发微信通知
            $data['approve'] = $approve;
            $data['action'] = 'wait';
            Hook::listen('send_sp_message',$data);

            return $approve;
        }
        //如果下个待审批人不存在，则完成审批流
        $approve->status = 'pass';
        $approve->wait_uid = 0;
        $approve->ext = json_encode($approve->setExt($approve, ['pass_time' => time()]));      // 审批通过时间
        $approve->save();

        //审批完成给发起人发微信通知
        $data['approve'] = $approve;
        $data['action'] = 'success';
        Hook::listen('send_sp_message',$data);

        return $approve;
    }

    //获取数组中的下一个单位
    public function arrayNextVal($array,$curr){
        $key = array_search($curr, $array);
        if ($key!== false && isset($array[$key + 1])) {
            $nextValue = $array[$key + 1];
            return $nextValue;
        } else {
            return false;
        }
    }
}
